package com.itheima.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JdbcDemo_Connection {
    public static void main(String[] args) throws Exception {

        //注册驱动  5.5版本后可以省略
        Class.forName("com.mysql.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://47.100.230.149:3306/myheima";
        String username = "myheima";
        String password = "myheima";
        /*String url = "jdbc:mysql:///day01_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false";
        //如果连接是本机mysql服务，端口为默认3306端口，那么可以省略不写
        // String url = "jdbc:mysql:///day01_test"
        String username = "root";
        String password = "123456";*/
        Connection conn = DriverManager.getConnection(url, username, password);

        //获取sql执行对象
        Statement statement = conn.createStatement();

        try {
            //开启事务
            conn.setAutoCommit(false);
            //定义sql
            String sql = "UPDATE account SET money = money + 500 WHERE id = 1";
            //执行sql
            int affNum = statement.executeUpdate(sql);
            //处理结果
            System.out.println("DML-受影响行数： " + affNum);
            //int a = 1/0;
            //定义sql
            String sql1 = "UPDATE account SET money = money - 500 WHERE id = 2";
            //执行sql
            int affNum1 = statement.executeUpdate(sql1);
            //处理结果
            System.out.println("DML-受影响行数： " + affNum);
            //提交事务
            conn.commit();
        } catch (Exception e) {
            //回滚事务
            conn.rollback();
            e.printStackTrace();
        }

        //释放资源
        statement.close();
        conn.close();
    }
}
